<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Utils\Context;
use App\Exception\ApiException;
use App\Constants\ErrorCode;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $uri = trim($request->getUri()->getPath(), '/');
        if (!in_array($uri, config('need_auth_uri'))) {    //不在此名单中的地址不用检测token
            return $handler->handle($request);
        }

        if(!$this->auth->check())
        {
            throw new ApiException(ErrorCode::ERR_HTTP_UNAUTHORIZED);
        }

        $request = Context::get(ServerRequestInterface::class);
        $request = $request->withAttribute('user_info', $this->auth->user());
        Context::set(ServerRequestInterface::class, $request);

        return $handler->handle($request);
    }
}